package com.base.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;

import tool.JsonTool;
import tool.TimeTool;

import com.base.bean.ClientBase;
import com.base.bean.MsessionBase;
import com.base.bean.MsessionObj;
import com.base.bean.MsessionUser;
import com.base.bean.User;
import com.base.dao.*;

@Deprecated
public class MsessionService {

	// 单例模式 start
	private volatile static MsessionService instance = null;

	private MsessionBaseDao baseDao;
	private MsessionReplyDao replyDao;
	private MsessionUserDao suDao;
	private MsessionObjDao soDao;

	private MsessionService() {
		baseDao = (MsessionBaseDao) _BaseDao.ac.getBean("MsessionBaseDao");
		replyDao = (MsessionReplyDao) _BaseDao.ac.getBean("MsessionReplyDao");
		suDao = (MsessionUserDao) _BaseDao.ac.getBean("MsessionUserDao");
		soDao = (MsessionObjDao) _BaseDao.ac.getBean("MsessionObjDao");
	}

	
	public static MsessionService getInstance() {
		if (instance == null) {
			synchronized (MsessionService.class) {// 1
				if (instance == null) {// 2
					instance = new MsessionService();// 3
				}
			}
		}
		return instance;
	}

	// 单例模式 end

	// showMsessionsByUser   showReplysByMsession
	
	
	
	private static Blob getBlob(Object object) {
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(
					byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			ByteArrayInputStream bis = new ByteArrayInputStream(
					byteArrayOutputStream.toByteArray());
			return Hibernate.createBlob(bis);
		} catch (Exception e) {
			return null;
		}
	}

	
	public List<MsessionBase> getListByUser(Integer uid){
		Session session=null;
		try{	
			session = this.baseDao.getSessionFactory().getCurrentSession();
			session.beginTransaction();	
			Query query = session.getNamedQuery("com.base.bean.msuser.getmsessions")
				.setInteger("uid", uid)
				.setTimestamp("now", TimeTool.getCurrentTime());
				
			List<MsessionBase> list = (List<MsessionBase>)query.list();  
			session.getTransaction().commit();
			if(list != null){  
			    return list;  
			}else 
				return null;	
		}finally{
			if(session.isOpen())
				session.close();
		}
	}
	
//	public int reflushLastTime(int msessionId,int uid){
//		Session session =null;
//		try{session = this.baseDao.getSessionFactory().getCurrentSession();
//			session.beginTransaction();			
//			String hqlUpdate = "update MsessionUser u set u.lastTime = :lastTime where u.sid= :sid and u.uid= :uid";
//			// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
//			int updatedEntities = session.createQuery( hqlUpdate )
//			        .setTimestamp( "lastTime",TimeTool.getCurrentTime())
//			        .setInteger("sid", msessionId)
//			        .setInteger("uid", uid)
//			.executeUpdate();
//			return 1;
//		}catch(Exception e){
//			e.printStackTrace();
//			session.beginTransaction().rollback();
//			return 0;
//		}finally{
//			if(session.isOpen())
//				session.close();
//		}
//	}
	
	/**
	 * 写对象的时候：无论时新增还是修改都等于新增
	 * @param id
	 * @param object
	 * @return
	 */
	public int saveObjectById(int msessionId,Object object) {
		Session session = null;
		MsessionObj msessionObj = null;
		try {
			
			session = soDao.getSessionFactory().openSession();
			
			msessionObj = (MsessionObj) session.get(MsessionObj.class, msessionId);
			msessionObj.setEntity(getBlob(object));
			
			Transaction tx = session.beginTransaction();
			session.update(msessionObj);
			tx.commit();
			return msessionId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			if (session.isOpen())
				session.close();
		}
	}
	
//	public int createSession(Integer creator,String title,String msg){
//		
//	}
	
	public int createMsession(MsessionBase msessionBase){
		Session session = null;
		try {
			session = baseDao.getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();
			session.save(msessionBase);
			
			@SuppressWarnings("unchecked")
			List<Integer> results = session
					.createCriteria(MsessionBase.class)
					.setMaxResults(1)
					.setProjection(
							Projections.projectionList().add(
									Projections.max("id"))

					).list();
			Integer maxId = results.get(0);
			MsessionObj msessionObj = new MsessionObj(maxId);
			msessionObj.setLastTime(TimeTool.getCurrentTime());
			
			session.save(msessionObj);
			
			
			tx.commit();
			return maxId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			if (session.isOpen())
				session.close();
		}
	}
	
//	public int createMsession(MsessionBase msessionBase,Object object){
//		Session session = null;
//		try {
//			session = baseDao.getSessionFactory().openSession();
//			Transaction tx = session.beginTransaction();
//			session.save(msessionBase);
//			
//			@SuppressWarnings("unchecked")
//			List<Integer> results = session
//					.createCriteria(MsessionBase.class)
//					.setMaxResults(1)
//					.setProjection(
//							Projections.projectionList().add(
//									Projections.max("id"))
//
//					).list();
//			Integer maxId = results.get(0);
//			MsessionObj msessionObj = new MsessionObj(maxId);
//			msessionObj.setLastTime(TimeTool.getCurrentTime());
//			msessionObj.setEntity(getBlob(object));
//			session.save(msessionObj);
//			
//			tx.commit();
//			return maxId;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return -1;
//		} finally {
//			if (session.isOpen())
//				session.close();
//		}
//	}
	
	
	/**添加接收者
	 * state=1
	 * @param sid
	 * @param uid
	 */
	public int addReceiver(int sid,int uid){
	try{	
		MsessionUser receiver = new MsessionUser();
		receiver.setSid(sid);
		receiver.setUid(uid);
		receiver.setState(1);
		this.getSuDao().save(receiver);
		return 1;
	}catch(Exception e){
		e.printStackTrace();
		return -1;
	}
	}
	
	
	public int updateSessionUser(int msessionId,int uid,String tip,int state){
		Session session =null;
		
		try{session = this.suDao.getSessionFactory().getCurrentSession();
			session.beginTransaction();	
			
			String hqlUpdate = "update MsessionUser a set a.tip= :tip,a.state= :state  where a.sid= :sid and a.uid = :uid ";
			// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
			int updatedEntities = session.createQuery( hqlUpdate )
			        .setInteger( "uid",uid)
			        .setInteger( "state",state)
			        .setString("tip", tip)
			        .setInteger( "sid",msessionId)	        
			.executeUpdate();
			return updatedEntities;
		}catch(Exception e){
			e.printStackTrace();
			session.beginTransaction().rollback();
			return 0;
		}finally{
			if(session.isOpen())
				session.close();
		}
	}
	
	public MsessionUser getMsessionUser(int msessionId,int uid){
		try{
		return this.getSuDao().findByHql("from MsessionUser mu where mu.sid="+msessionId+" and mu.uid="+uid).get(0);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	

	
	public int changeState(int msessionId,int state){
		Session session =null;
		
	try{session = this.baseDao.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		
		String hqlUpdate = "update MsessionBase a set a.state = :state where a.id= :id ";
		// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
		int updatedEntities = session.createQuery( hqlUpdate )
		        .setInteger( "state",state)
		        .setInteger( "id",msessionId)	        
		.executeUpdate();
		return updatedEntities;
	}catch(Exception e){
		e.printStackTrace();
		session.beginTransaction().rollback();
		return 0;
	}finally{
		if(session.isOpen())
			session.close();
	}
	}
	
	/**
	 * 
	 * @param id:MsessionBase's id
	 * @return
	 */
	public Object readObjectById(int msessionId) {
		Session session = null;
		try {
			session = soDao.getSessionFactory().openSession();
			MsessionObj test = (MsessionObj) session.get(MsessionObj.class, msessionId);
			ObjectInputStream objectInputStream = new ObjectInputStream(test
					.getEntity().getBinaryStream());
			return objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (session.isOpen())
				session.close();
		}
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
//		
//		MsessionService s = MsessionService.getInstance();
//		
////		MsessionBase msessionBase = new MsessionBase();
////		User user = new User();
////		user.setName("li5");
//////		int r = s.createMsession(msessionBase,user);
////		int r =s.saveObjectById(11,  user);
////		System.out.println(r);
//		
//		List<MsessionBase> list = s.getListByUser(36, 1);
//		System.out.println(JsonTool.obj2json(list));
////		
////		for (MsessionBase b:list){
////			String str =b.toString();
////			System.out.println(str);
////
////			System.out.println(b.getdiscription());
////		}
//		
//		User user1 = (User)s.readObjectById(10);
//		System.out.println(user1.getName());
		
	}

	public MsessionBaseDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(MsessionBaseDao baseDao) {
		this.baseDao = baseDao;
	}

	public MsessionReplyDao getReplyDao() {
		return replyDao;
	}

	public void setReplyDao(MsessionReplyDao replyDao) {
		this.replyDao = replyDao;
	}

	public MsessionUserDao getSuDao() {
		return suDao;
	}

	public void setSuDao(MsessionUserDao suDao) {
		this.suDao = suDao;
	}

	public MsessionObjDao getSoDao() {
		return soDao;
	}

	public void setSoDao(MsessionObjDao soDao) {
		this.soDao = soDao;
	}

}
